<template>
  <el-dialog
    title="修改头像"
    v-model="visible"
    width="400px"
  >
    <el-upload
      class="avatar-uploader"
      action="/api/upload/avatar"
      :show-file-list="false"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" :key="imageUrl" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button
        type="primary"
        @click="confirmAvatar"
        :disabled="!imageUrl"
      >
        确认
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { Plus } from '@element-plus/icons-vue'

export default {
  name: 'AvatarDialog',
  components: { Plus },
  props: {
    modelValue: Boolean
  },
  emits: ['update:modelValue', 'success'],
  data() {
    return {
      imageUrl: '',
      uploadHeaders: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    }
  },
  computed: {
    visible: {
      get() { return this.modelValue },
      set(value) { this.$emit('update:modelValue', value) }
    }
  },
  methods: {
    beforeUpload(file) {
      const isValid = file.type.startsWith('image/')
      const isWithinSize = file.size / 1024 / 1024 < 2

      if (!isValid) this.$message.error('请上传图片文件')
      if (!isWithinSize) this.$message.error('图片大小不能超过2MB')

      if (isValid && isWithinSize) {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.imageUrl = reader.result
        }
      }

      return false // 手动上传
    },
    confirmAvatar() {
      this.$emit('success', this.imageUrl)
      this.visible = false
      this.imageUrl = ''
    }
  }
}
</script>

<style scoped>
.avatar-uploader {
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
  margin: 0 auto;
  border-radius: 50%;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}
</style>